class EventEmitter {
  constructor() {
    this._events = {};
  }
  on(eventName, func) {
    if (!this._events) {
      this._events = {};
    }
    if (eventName !== "newListener") {
      // 可以让用户监听某个时间，来监控后续的操作.
      this.emit("newListener", eventName);
    }
    (this._events[eventName] || (this._events[eventName] = [])).push(func);
  }
  once(eventName, func) {
    let once = (...args) => {
      func(...args); // 原始要执行的函数
      this.off(eventName, once);
    };
    once.l = func; // 自定义属性
    this.on(eventName, once);
  }

  emit(eventName, ...args) {
    if (!this._events) this._events = {};
    if (this._events[eventName]) {
      this._events[eventName].forEach((func) => {
        func(...args);
      });
    }
  }

  off(eventName, func) {
    if (!this._events) this._events = {};
    if (this._events[eventName]) {
      this._events[eventName] = this._events[eventName].filter(
        (item) => item !== func && item.l !== func
      );
    }
  }
}
module.exports = EventEmitter;
